package com.ruoyi.charge.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.charge.service.WXService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

@Component
public class WXServiceImpl implements WXService {

    private static final Logger logger = LoggerFactory.getLogger(WXServiceImpl.class);

    private static final String urlPre = "https://anninfo.cn/image/qrcode/";

    @Autowired
    private RedisCache redisCache;

    @Override
    public String generateQrcode(Long equipmentId, Long storeId, String tableNumber) {
        //获取accessToken
        String accessToken = this.getAccessToken(false);
        String scene = equipmentId.toString() + "&" + storeId.toString() + "&" + tableNumber;
        String qrCode = postMiniQrCode(scene, accessToken);
        return qrCode;
    }

    @Override
    public String getAccessToken(Boolean forceFlag) {
        if (!forceFlag) {
            if (redisCache.existKey("charge_obtain_weixin_access_token")) {
                Object object = redisCache.getCacheObject("charge_obtain_weixin_access_token");
                return object.toString();
            }
        }
        try {
            //获取AccessToken
            String apiKey = "wx40bd649374e36f03";//小程序id
            String secretKey = "fec157be241fc0a68e5fe7aaf1119b0b";//小程序**
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + apiKey + "&secret=" + secretKey;
            URL url = new URL(requestUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setDoInput(true);

            // 得到请求的输出流对象
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes("");
            out.flush();
            out.close();

            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = null;
            if (requestUrl.contains("nlp"))
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
            else
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String result = "";
            String getLine;
            while ((getLine = in.readLine()) != null) {
                result += getLine;
            }
            in.close();

            JSONObject jsonObject = JSON.parseObject(result);

            String accesstoken = jsonObject.getString("access_token");
            Integer expires_in = jsonObject.getInteger("expires_in");
            Integer diff = 100;
            //缓存
            redisCache.setCacheObject("charge_obtain_weixin_access_token", accesstoken, expires_in, TimeUnit.SECONDS);
            return accesstoken;
        } catch (Exception e) {
            logger.error("charge_obtain_weixin_access_token_error, error信息：{}", e.getMessage(), e);
        }
        return null;
    }


    public String postMiniQrCode(String scene, String accessToken) {
        try {
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true); // 打开写入属性
            httpURLConnection.setDoInput(true); // 打开读取属性
            httpURLConnection.setRequestMethod("POST");// 提交方式
            // 一定要记得加响应头
            httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");// 设置响应头
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", scene); // 你要放的内容
            paramJson.put("path", "pages/index/index");
            paramJson.put("width", 430); // 宽度
            paramJson.put("auto_color", true);
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            //创建一个空文件
            File file = new File("./images/"+scene+".jpg");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
            OutputStream os = new FileOutputStream(file);
            //ByteArrayOutputStream os = new ByteArrayOutputStream();
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();

            return urlPre+scene+".jpg";


        } catch (Exception e) {
            logger.error("charge_post_mini_weixin_qrcode_error, error信息：{}", e.getMessage(), e);
        }
        return null;
    }


}
